package cn.inbot.shopadmin.module.mine.viewmodel;

import androidx.lifecycle.MutableLiveData;

import cn.inbot.shopadmin.api.DemoApiFactory;
import cn.inbot.shopadmin.app.AppCacheData;
import cn.inbot.shopadmin.app.AppGlobalData;
import cn.inbot.shopadmin.bean.LoginResult;
import cn.inbot.shopadmin.event.OnLoginEvent;
import cn.inbot.shopadmin.module.mine.repository.LoginRepository;
import cn.inbot.lib.framework.EventManager;
import cn.inbot.lib.framework.mvvm.java.ApiCallbackAdapter;
import cn.inbot.lib.framework.mvvm.java.PBJViewModel;
import cn.inbot.lib.network.ResponseWrapper;
import cn.inbot.lib.util.JsonUtil;
import cn.inbot.lib.util.StringUtil;
import cn.inbot.lib.widget.LoadingDialogHelper;

import static cn.inbot.lib.util.ext.ToastExtKt.showToast;

/**
 * Created by shisenkun on 2021/5/11.
 */
public class LoginViewModel extends PBJViewModel {
    private final LoginRepository mRepository = new LoginRepository();
    public MutableLiveData<ResponseWrapper<LoginResult>> loginResponseWrapper = new MutableLiveData();

    public void login(String username, String password, String androidId) {

        if(StringUtil.isEmpty(username)) {
            showToast("请输入用户名");
            LoadingDialogHelper.INSTANCE.hide();
            return;
        }
        if(StringUtil.isEmpty(password)) {
            showToast("请输入密码");
            LoadingDialogHelper.INSTANCE.hide();
            return;
        }

        AppCacheData.setLastLoginUsername(username);
        AppCacheData.setLastLoginPassword(password);

        apiCall(mRepository.login(username, password, androidId),
                new ApiCallbackAdapter<ResponseWrapper<LoginResult>>() {
                    @Override
                    public void onCompleted(ResponseWrapper<LoginResult> responseWrapper) {
                        super.onCompleted(responseWrapper);
                        loginResponseWrapper.setValue(responseWrapper);
                        if(responseWrapper.getData() != null) {
                            //追加签名参数
                            DemoApiFactory.getInstance().autographParamsMap.put("username", responseWrapper.getData().getUsername());
                            DemoApiFactory.getInstance().autographParamsMap.put("loginuuid", responseWrapper.getData().getLoginUuid());
                            AppGlobalData.sLoginResult = responseWrapper.getData();
                            AppCacheData.setLastLoginResultJson(JsonUtil.objectToJson(responseWrapper.getData()));
                            EventManager.INSTANCE.post(new OnLoginEvent());
                        }
                    }
                });

    }

}

